package cn.caidabao.gb.component.sip.server.response.recieve;

import cn.caidabao.gb.bean.OGSipCallIdCallBack;
import cn.caidabao.gb.component.sip.CustomSipServer;
import cn.caidabao.gb.component.sip.server.storage.CallBackStorage;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.sip.ResponseEvent;
import javax.sip.header.CSeqHeader;
import javax.sip.header.CallIdHeader;
import javax.sip.message.Request;
import javax.sip.message.Response;

@Slf4j
@Component
public class RecieveByeMessageResponseHandler implements ResponseHandler{
    @Resource
    private CallBackStorage callBackStorage;
    @SneakyThrows
    @Override
    public void handleResponse(ResponseEvent responseEvent) {
        Response response = responseEvent.getResponse();
        CSeqHeader cSeqHeader = (CSeqHeader) response.getHeader(CSeqHeader.NAME);
        CallIdHeader callIdHeader = (CallIdHeader) response.getHeader(CallIdHeader.NAME);
        String callId = callIdHeader.getCallId();
        OGSipCallIdCallBack callBack = callBackStorage.getAndDeleteCallBack(callId);
        if (callBack==null){
            log.warn("在处理bye请求时没有找到对应的callBack");
            return;
        }
        Boolean result = null;
        if (response.getStatusCode()==200){
            responseEvent.getDialog().createAck(cSeqHeader.getSeqNumber());
            Request ack = responseEvent.getClientTransaction().createAck();
            CustomSipServer.server.udpSipProvider.sendRequest(ack);
            result = true;
        }else {
            result = false;
        }
        callBack.setResult(result);
    }
}
